<?php

namespace App\Service\GuanyuanSSO;

use App\Enums\BaseErrorCode;
use App\Exceptions\Custom\ResponseHttpException;
use App\Models\Guanyuan\GuanyuanAccountBindModel;
use App\Models\Guanyuan\GuanyuanAccountModel;
use App\Models\Kms\User\KmsUser;
use App\Service\OpenShop\Feishu\ConfigService;
use Illuminate\Http\Request;

class GuanyuanAccountService
{

    /**
     * 添加
     * @param Request $request
     * @param int $userId
     * @return array
     */
    public static function add(Request $request, int $userId): array
    {
        $count = GuanyuanAccountModel::query()
            ->where('guanyuanId', $request->guanyuanId)
            ->count();
        if ($count) {
            throw new ResponseHttpException(BaseErrorCode::$ERROR_OCCURRED, null, "观远账号ID已存在");
        }
        try {
            $m = new GuanyuanAccountModel();

            $m->guanyuanId   = $request->guanyuanId;
            $m->name         = $request->name;
            $m->desc         = $request->desc ?? '';
            $m->createdByUid = $userId;
            $m->save();
            return ['id' => $m->id];
        } catch (\Exception $e) {
            throw new ResponseHttpException(BaseErrorCode::$ERROR_OCCURRED, null, "添加失败");
        }
    }

    /**
     * 编辑
     * @param Request $request
     * @param int $id
     * @param int $userId
     */
    public static function update(Request $request, int $id, int $userId)
    {
        $info = GuanyuanAccountModel::query()->find($id);
        if (!$info) {
            throw new ResponseHttpException(BaseErrorCode::$ERROR_OCCURRED, null, "不存在的记录id");
        }
        try {
//            $info->guanyuanId   = $request->guanyuanId;
            $info->name         = $request->name;
            $info->desc         = $request->desc ?? '';
            $info->updatedByUid = $userId;
            $info->save();
        } catch (\Exception $e) {
            throw new ResponseHttpException(BaseErrorCode::$ERROR_OCCURRED, null, "编辑失败");
        }
    }

    /**
     * info
     * @param int $id
     */
    public static function info(int $id): array
    {
        $info = GuanyuanAccountModel::query()
            ->with(['bindRel'])
            ->find($id);
        if (!$info) {
            throw new ResponseHttpException(BaseErrorCode::$ERROR_OCCURRED, null, "不存在的记录id");
        }

        $bindData = [];
        if (count($info->bindRel)) {
            $fsUserIds  = $info->bindRel->pluck("fsUserId")->toArray();
            $fsUserList = KmsUser::query()->whereIn('userId', $fsUserIds)->get()->keyBy('userId')->toArray();
            collect($info->bindRel)->map(
                function ($item) use ($fsUserList, &$bindData) {
                    $bindData[] = [
                        'fsUserId'           => $item->fsUserId,
                        'nickname'           => ($fsUserList[$item->fsUserId]['nickname'] ?? '') . '(' . ($fsUserList[$item->fsUserId]['name'] ?? '') . ')',
                        'rootDepartmentName' => $fsUserList[$item->fsUserId]['rootDepartmentName'] ?? '',
                    ];

                }
            );
        }

        return [
            "id"         => $info->id,
            "guanyuanId" => $info->guanyuanId,
            "name"       => $info->name,
            "desc"       => $info->desc,
            "createdAt"  => $info->createdAt->toDateTimeString(),
            "bindData"   => $bindData,
        ];
    }

    /**
     * 删除
     * @param int $id
     * @param int $userId
     */
    public static function del(int $id, int $userId)
    {
        $info = GuanyuanAccountModel::query()->find($id);
        if (!$info) {
            throw new ResponseHttpException(BaseErrorCode::$ERROR_OCCURRED, null, "不存在的记录id");
        }
        $getBindCount = GuanyuanAccountBindModel::getCount($id);
        if ($getBindCount > 0) {
            throw new ResponseHttpException(BaseErrorCode::$ERROR_OCCURRED, null, "存在绑定数据不能删除");
        }
        try {
            $info->isDeleted    = 1;
            $info->updatedByUid = $userId;
            $info->save();
        } catch (\Exception $e) {
            throw new ResponseHttpException(BaseErrorCode::$ERROR_OCCURRED, null, "删除失败");
        }
    }

    /**
     * 获取列表
     * @param string $username
     * @param string $mobile
     * @param string $guanyuanId
     * @param int $pageSize
     * @param int $pageNum
     * @return array
     */
    public static function getList(string $username, string $mobile, string $guanyuanId, int $pageSize, int $pageNum): array
    {
        $fsUserIds = [];
        if ($username || $mobile) {
            $fsUserIds = KmsUser::query()
                ->when(
                    $username, function ($query) use ($username) {
                    $query->where(
                        function ($query) use ($username) {
                            $query->where("name", "like", "%$username%")->orWhere("nickname", "like", "%$username%");
                        }
                    );
                }
                )
                ->when(
                    $mobile, function ($query) use ($mobile) {
                    $query->where('mobile', $mobile);
                }
                )
                ->pluck('userId')->values()->unique()->toArray();
        }
        $paginator = GuanyuanAccountModel::query()
            ->with(['bindRel'])
            ->when(
                $guanyuanId, function ($query) use ($guanyuanId) {
                $query->where('guanyuanId', "like", "%$guanyuanId%");
            }
            )
            ->when(
                $fsUserIds, function ($query) use ($fsUserIds) {
                $guanyuanAccountIds = GuanyuanAccountBindModel::query()
                    ->whereIn('fsUserId', $fsUserIds)
                    ->pluck('guanyuanAccountId')->values()->toArray();
                $query->whereIn('id', $guanyuanAccountIds);
            }
            )
            ->orderByDesc('createdAt')
            ->paginate($pageSize, ['*'], 'pageNum', $pageNum);

        $lists = $paginator->map(
            function (GuanyuanAccountModel $guanyuanAccountModel) {
                return [
                    'id'         => $guanyuanAccountModel->id,
                    'guanyuanId' => $guanyuanAccountModel->guanyuanId,
                    'name'       => $guanyuanAccountModel->name,
                    'desc'       => $guanyuanAccountModel->desc,
                    'createdAt'  => $guanyuanAccountModel->createdAt->toDateTimeString(),
                    'bindCount'  => count($guanyuanAccountModel->bindRel),
                ];
            }
        );
        return [
            'pageNum'   => $paginator->currentPage(),
            'pageSize'  => $paginator->perPage(),
            'pageCount' => ceil($paginator->total() / $paginator->perPage()),
            'count'     => $paginator->total(),
            'lists'     => $lists,
        ];
    }


    /**
     * 添加绑定
     * @param Request $request
     * @param int $id
     * @param int $userId
     */
    public static function bindAdd(Request $request, int $id, int $userId)
    {
        $info = GuanyuanAccountModel::query()->find($id);
        if (!$info) {
            throw new ResponseHttpException(BaseErrorCode::$ERROR_OCCURRED, null, "不存在的记录id");
        }
        if ($request->fsUserId) {
            $isBindCount = GuanyuanAccountBindModel::query()
                ->whereIn('fsUserId', $request->fsUserId)
                ->where('guanyuanAccountId', '!=', $id)
                ->count();
            if ($isBindCount) {
                throw new ResponseHttpException(BaseErrorCode::$ERROR_OCCURRED, null, "存在用户已绑定其他观远账号");
            }
        }
        try {
            GuanyuanAccountBindModel::query()->where('guanyuanAccountId', $id)->update(['isDeleted' => 1, 'updatedByUid' => $userId]);

            if ($request->fsUserId) {
                $data = [];
                foreach ($request->fsUserId as $v) {
                    $data[] = [
                        'fsUserId'          => $v,
                        'guanyuanAccountId' => $id,
                        'createdAt'         => time(),
                        'createdByUid'      => $userId,
                    ];
                }
                if ($data) {
                    GuanyuanAccountBindModel::insertData($data);
                }
            }
        } catch (\Exception $e) {
            throw new ResponseHttpException(BaseErrorCode::$ERROR_OCCURRED, null, "绑定失败");
        }
    }

    /**
     * 获取飞书一级部门下用户
     * @return array
     */
    public static function fsUserList(): array
    {
        $data = [];
        KmsUser::query()
               ->where("rootDepartmentName", "<>", "")
               ->where("isExited", 0)//是否已离职
               ->where("resignedTime", 0)//离职时间
               ->groupBy('userId')
               ->get()
               ->map(
                   function ($item) use (&$data) {
                       if (isset($data[$item['rootDepartmentName']])) {
                           $data[$item['rootDepartmentName']][] = [
                               'userId'             => $item['userId'],
                               'nickname'           => $item['nickname'] . '(' . $item['name'] . ')',
                               'rootDepartmentName' => $item['rootDepartmentName'],
                           ];
                       } else {
                           $data[$item['rootDepartmentName']][] = [
                               'userId'             => $item['userId'],
                               'nickname'           => $item['nickname'] . '(' . $item['name'] . ')',
                               'rootDepartmentName' => $item['rootDepartmentName'],
                           ];
                       }
                   }
               );

        $outOrganization = ConfigService::config('guanyuanSSO', 'outOrganization')['outOrganization'];

        $data = array_merge($data, $outOrganization);

        return $data;
    }


    /**
     * 通过飞书用户id查询绑定的观远账号id
     * @param string $fsUserId
     * @return string
     */
    public static function getGuanyuanSSOUserIdByFsUserId(string $fsUserId): string
    {
        $bindInfo = GuanyuanAccountBindModel::query()
            ->with(['guanyuanAccountRel'])
            ->where('fsUserId', $fsUserId)
            ->first();
        return $bindInfo->guanyuanAccountRel->guanyuanId ?? '';

    }


    /**
     * 获取已绑定的用户
     */
    public static function getBindFsUser(): array
    {
        return GuanyuanAccountBindModel::query()->select(['fsUserId'])->get()->pluck('fsUserId')->toArray();
    }
}
